import json
import os.path
import time
import threading
from libs.comps.common.component import manager , TComponentManager , TComponent
import schedule

tplSchedule ={
    "schCode":"",
    "schType":"min", # sec , min , hur , day
    "timeNum": 1 ,
    "ats":["11:11:11","11:11",":11"] ,
    "tag":{}
}

class TCompSchedule( TComponent):
    def __init__(self, _manager):
        super().__init__(_manager)
        self.info ={
            'schedules':{}
        }
        self.schedules ={}
    def init(self):
        try:
            pass
        except Exception as er:
            self.manager.log(self , er)
    def loadSchedule(self):
        try:
            schedule.clear()
            schedule.every().days.tag()
            for schItem in self.info['schedules'].values():
                try:
                    schCode = schItem['schCode']
                    schType = schItem['schType']
                    timeNum = schItem['timeNum']
                    ats = schItem['ats']
                    tag = schItem['tag']
                    tag['schCode'] = schCode
                    schList =[]

                    sch = None
                    if schType=="sec":
                        sch = schedule.every(timeNum).seconds
                    elif schType=="min":
                        sch = schedule.every(timeNum).minutes
                    elif schType=="hur":
                        sch = schedule.every(timeNum).hours
                    elif schType=="day":
                        sch = schedule.every(timeNum).days
                    if sch!=None :
                        if ats!=None and len(ats)>0:
                            for at in ats:
                                sch_at = sch.at(at)
                                if tag ==None :
                                    tag = {}
                                tag['at'] = at
                                schList.append(sch_at)
                        else:
                            schList.append(sch)

                    for schImp in schList:
                        schCode = tag['schCode']
                        tagData =json.dumps(tag , ensure_ascii=False)
                        schImp.tag(tagData)
                        sch.do(self.scheduleJob, schCode= schCode)
                except Exception as erItem:
                    self.manager.log(self , erItem)
            print(schedule)
        except Exception as er:
            self.manager.log(self , er)
    def scheduleJob(self , schCode):
        pass
    def serviceHandler(self):
        try:
            super().serviceHandler()
            schedule.run_all(2)
            while self.running :
                schedule.run_pending()
                time.sleep(1)
            schedule.clear()
        except Exception as erBrfore:
            self.manager.log(self, erBrfore)
    def beforeStartService(self):
        try:
            super().beforeStartService()
            self.init()
            self.loadSchedule()
        except Exception as er:
            self.manager.log(self, er)
    def startService(self):
        try:
            if not self.running:
                try:
                    self.beforeStartService()
                except Exception as erBrfore:
                    self.manager.log(self, erBrfore)
                self.serviceThread = threading.Thread(target=self.serviceHandler , daemon=True)
                self.running = True
                self.serviceThread.start()
        except Exception as er:
            self.manager.log(self, er)
    def stopService(self):
        try:
            self.running = False
            schedule.clear()
        except Exception as er:
            self.manager.log(self, er)
